import {abstractValidator} from "../validator/abstractValidator";
import {mc_validatorResult} from "../model/mc_validatorResult";
/**
 * Created by ybjaa on 2017/7/3.
 *
 * 获得对象实例的验证结果（同一原型链的对象子类的会覆盖父类的）
 *
 */
export function getValidators(){


    return function (target:any,propertyName:string,properyDescriptor:PropertyDescriptor) {

        let oldvalue=properyDescriptor.value;

        properyDescriptor.value=function () {

            let objPropto=this.constructor.prototype;

            let map:Map<Object, Map<string,abstractValidator[]> > =objPropto[Symbol.for("validator")];

            if(!map||map.size<=0) return oldvalue.call(this,true,null);

            let targetMap:Map<string,abstractValidator[]> =null;
            //let thisTargetMap:Map<string,abstractValidator[]>=map.get(this.constructor.prototype);

            let validators=new Array<mc_validatorResult>();

            let clearPropertyMap:Map<Object,string[]>=objPropto[Symbol.for("clearValidator")];

            let clearPropertys:string[]=[];



            let thisObj=this;




            while (objPropto){

                targetMap=map.get(objPropto);
                if(targetMap&&targetMap.size>0){

                    targetMap.forEach((v,k)=>{
                        if(!clearPropertys.some((value)=>value==k))
                            validators=validators.concat(v.map(v=>v.validator(thisObj[k],thisObj)).filter(v=>v!=null))
                    });
                }

                if(clearPropertyMap&&clearPropertyMap.has(objPropto)){
                    clearPropertys=clearPropertys.concat(clearPropertyMap.get(objPropto));
                }

                objPropto=Reflect.getPrototypeOf(objPropto);
            }

            let falseValidators= validators.filter((v=>!v.result));

            if(falseValidators.length>0){
                return oldvalue.call(this,false,falseValidators);
            }else {
                return oldvalue.call(this,true,null);
            }
        }


        return properyDescriptor;





    }
    

}